package com.tqw.es.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;

/**
 * @author Jim
 */
@Configuration
@ConditionalOnBean(ElasticsearchRestTemplate.class)
public class AutoCreateIndexConfig {
    @Value("${es.indexname}")
    private static String indexname;
    @Value("${es.classname}")
    private static String classname;
    @Autowired
    private static ElasticsearchRestTemplate restTemplate;

    static {
        if (!indexExists(indexname)){
            try {
                createIndex(indexname, classname);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public static Boolean indexExists(String indexname){
        return restTemplate.indexOps(IndexCoordinates.of(indexname)).exists();
    }

    public static void createIndex(String indexname,String classname) throws ClassNotFoundException {
        Document mapping = restTemplate.indexOps(IndexCoordinates.of(indexname)).createMapping(Class.forName(classname));
        restTemplate.indexOps(IndexCoordinates.of(indexname)).putMapping(mapping);
    }
}
